#include "Document.h"

#include "LeGerber/filereader.h"
#include "LeGerber/command.h"
#include "LeGerber/processor.h"
#include "LeGerber/object.h"
#include "LeGerber/graphicsscene.h"

#include <QFile>

using namespace LeGerber;

namespace GerberViewer
{

    Document::Document(QObject *parent):
        IDocument(parent),
        m_scene(new GraphicsScene(this))
    {

    }

    bool Document::open(QString *errorString, const QString &fileName)
    {

        QFile file(fileName);

        if (!file.open(QFile::ReadOnly))
        {
            *errorString = QString("While opening: %1").arg(file.errorString());
            return false;
        }

        if (file.bytesAvailable() > 1024*1024) // 20MB => 1+ millions of objects
        {
            *errorString = QString("While opening: File too big");
            return false;
        }

        const QByteArray data = file.readAll();

        FileReader reader;
        reader.setData(data);
        if (!reader.parse())
        {
            //warning(reader.warnings());
            *errorString = QString("While parsing: %1").arg(reader.errorString());
            return false;
        }

        QList<Command*> commands = reader.takeCommands();
        //warning(reader.warnings());

        Processor processor;
        for (auto command: commands)
        {
            command->execute(&processor);
            if (processor.isError())
            {
                qDeleteAll(commands);
                //warning(processor.warningMessages());
                *errorString = QString("While processing: %1").arg(processor.errorMessage());
                return false;
            }
        }
        qDeleteAll(commands);

        m_objects = processor.takeObjects();
        //warning(processor.warningMessages());

        m_scene->clear();
        m_scene->setDarkBrush(QBrush(QColor("#2aa198")));
        m_scene->setDarkPen(QPen(Qt::NoPen));
        m_scene->setClearBrush(QBrush(QColor("#002b36")));
        m_scene->setClearPen(QPen(Qt::NoPen));
        for (auto object: m_objects)
        {
            m_scene->addGerberObject(object);
            //delete object;
        }
        //m_objects.clear();
        return true;
    }

    GraphicsScene *Document::scene()
    {
        return m_scene;
    }

    bool Document::save(QString *errorString, const QString &fileName)
    {
        Q_UNUSED(fileName);

        if (errorString != nullptr)
        {
            *errorString = QStringLiteral("Saving Gerber file is not supported");
        }

        return false;
    }

    void Document::render(QPainter *painter)
    {
        Q_UNUSED(painter);
    }

}
